<?php
require_once(CORE_DIR.'Common.php');
require_once(CORE_DIR.'Model.php');
require_once(CORE_DIR.'mappers/UserMapper.php');
require_once(CORE_DIR.'mappers/CountMapper.php');

class userModel extends Model{

	function __construct(){
		$this->conn = $this->getConnection();
	}

	public function isLoggedIn() {
		if(isset($_SESSION[SESSION_USER_OBJECT]))
			return true;
		else
			return false;
	}

	public function isAutoLoggedIn() {
		$query = "select * from autologin where session='%s'";
		$query = $this->format($query, array(session_id()));
		$result = mysqli_query($this->conn, $query);
		$retVal = false;
		if($row = mysqli_fetch_array($result))
		{
			$query = "select * from user where id=%d";
			$query = $this->format($query, array($row['userid']));
			$userDto = $this->execute($query, new UserMapper());
			if(count($userDto) > 0)
			{
				$this->setActiveUser($userDto[0]);
				$retVal = true;
			}
		}
		mysqli_free_result($result);
		return $retVal;
	}

	public function saveAutologinData($userId, $session) {
		$query = "INSERT INTO autologin VALUES(%d, '%s')";
		$query = $this->format($query, array($userId, $session));
		return mysqli_query($this->conn, $query);
	}
	
	public function removeAutologinData() {
		$query = "DELETE FROM autologin WHERE session = '%s'";
		$query = $this->format($query, array(session_id()));
		return mysqli_query($this->conn, $query);
	}
	
	public function getActiveUser() {
		if(isset($_SESSION))
			return $_SESSION[SESSION_USER_OBJECT];

		return null;
	}
	
	public function setActiveUser($userDto) {
		if(!isset($_SESSION)) {
			session_start();
		}
		
		$_SESSION[SESSION_USER_OBJECT] = $userDto;
	}
	
	public function login($email, $pass)
	{
		if($email == '' || $pass == '')
		{
			return null;
		}
		$hash = $pass;
		$query = "select * from user where email='%s' and password='%s'";
		$query = $this->format($query, array($email,$hash));
		$userDto = $this->execute($query, new UserMapper());
		return $userDto[0];
	}
	
	public function fblogin($fbuid)
	{
		if($fbuid == '')
		{
			return null;
		}
		$query = "select * from user where fbuid='%s'";
		$query = $this->format($query, array($fbuid));
		$userDto = $this->execute($query, new UserMapper());
		return $userDto[0];
	}
	
	protected function getPasswordHash($password)
	{
		$hash = md5($password);
		return $hash;
	}
	
	function addUser($userNick, $userFName, $userLName, $userRole, $userEmail, $userPass, $taskType, $fbUid){
		$query = "insert into user (nickName, firstName, lastName, role, email, password, tasktype, fbuid)
				  values ('%s', '%s', '%s', '%d', '%s', '%s', '%d', '%s')";
		$query = $this->format($query, array($userNick, $userFName, $userLName, $userRole, $userEmail, $userPass, $taskType, $fbUid));
		
		mysqli_query($this->conn, $query);
		return mysqli_insert_id($this->conn);
	}

	function updateUser($id, $userNickName, $userFName, $userLName, $userRole, $userEmail, $userPass, $taskType, $fbUid){
		$query = "UPDATE user SET nickName='%s', firstName='%s', lastName='%s', role=%d, email='%s', password='%s', tasktype=%d, fbuid='%s' WHERE id=%d";
		$query = $this->format($query, array($userNickName, $userFName, $userLName, $userRole, $userEmail, $userPass, $taskType, $fbUid, $id));
		return mysqli_query($this->conn, $query);
	}

	function deleteUser($id){
		$query = "delete from user where id=%d";
		$query = $this->format($query, array($id));		
		if(mysqli_query($this->conn, $query))
			return $this->deleteTasksFromUser($id);
		return false;		
	}		
	
	function deleteTasksFromUser($userId){
		$query = "delete from taskuser where userId=%d";
		$query = $this->format($query, array($userId));		
		return mysqli_query($this->conn, $query);		
	}


	public function getAllUsers(){
		$activeUser = $this->getActiveUser();
		
		$query = "SELECT u.*, UPPER(u.nickName) AS name  
					FROM user u
					" . ($activeUser->getRole() == 2 ? " WHERE u.id IN (SELECT userID FROM permissions WHERE projectID IN (SELECT projectID FROM permissions WHERE userID = {$activeUser->getId()}))" : "") . "
					ORDER BY  u.nickName, u.id";
		
		$result = mysqli_query($this->conn, $query);
		
		$users = array();
		while ($user = mysqli_fetch_assoc($result)){
			$users[$user["id"]]["id"] = $user["id"];
			$users[$user["id"]]["nickname"] = $user["name"];
		}
		
		mysqli_free_result($result);
		return $users;
	}
	
	
	public function getUsersList(){
		$activeUser = $this->getActiveUser();
		
		$query = "SELECT u.*, UPPER(u.nickName) AS name, gr.id as group_id, gr.name as group_name  
					FROM user u
					LEFT JOIN grouptouser gu ON gu.userId = u.id 
					LEFT JOIN `group` gr ON gu.groupId = gr.id
					" . ($activeUser->getRole() == 2 ? " WHERE u.id IN (SELECT userID FROM permissions WHERE projectID IN (SELECT projectID FROM permissions WHERE userID = {$activeUser->getId()}))" : "") . "
					ORDER BY  u.nickName, u.id";
		$result = mysqli_query($this->conn, $query);
		
		$users = array();
		while ($user = mysqli_fetch_assoc($result)){
			if ($users[count($users)-1]["id"] == $user["id"]){
				$users[count($users)-1]["group_id"] .= "|".$user["group_id"];
				$users[count($users)-1]["group_name"] .= "|".$user["group_name"];
			}
			else{
				$user["imagesList"] = $this->getImagesByUserId($user["id"]);				
				$users[] = $user;
			}
		}
		
		mysqli_free_result($result);
		return $users;
	}
	
	public function getUsersData($userid){
		$query = "SELECT u.* , gr.id as group_id, gr.name as group_name 
					FROM user u
					LEFT JOIN grouptouser gu ON gu.userId = u.id 
					LEFT JOIN `group` gr ON gu.groupId = gr.id
					WHERE u.id=%d";
		$query = $this->format($query, array($userid));		
		$result = mysqli_query($this->conn, $query);

		$row = mysqli_fetch_assoc($result);
		mysqli_free_result($result);
		return $row;
	}
	
	
	public function getFullUsersList(){
		$query = "SELECT u.* , gr.id as group_id, gr.name as group_name 
					FROM user u
					LEFT JOIN grouptouser gu ON gu.userId = u.id 
					LEFT JOIN `group` gr ON gu.groupId = gr.id
					ORDER BY u.nickName, u.id";
		$result = mysqli_query($this->conn, $query);
		
		$users = array();
		while ($user = mysqli_fetch_assoc($result)){
			if ($users[count($users)-1]["id"] == $user["id"]){
				$users[count($users)-1]["group_id"] .= "|".$user["group_id"];
				$users[count($users)-1]["group_name"] .= "|".$user["group_name"];
			}
			else{
				$user["imagesList"] = $this->getImagesByUserId($user["id"]);			
				$users[] = $user;
			}
		}
		
		mysqli_free_result($result);
		return $users;
	}

	/*
	 * $doneTasks - if set 0 will retrive list of users with active tasks
	 * if 1- will retrive list of users with done tasks
	 * */
	public function getUsersListByProject($projectID, $doneTasks, $period){
		$activeUser = $this->getActiveUser();
		
		$dateRange = getDatesRange($period);
		$query = "SELECT u.*, UPPER(u.nickName) AS name, COUNT(t.id) as taskCount 
			FROM task t
			LEFT JOIN taskuser tu ON tu.taskId = t.id 
			LEFT JOIN `user` u ON tu.userId = u.id 
			WHERE t.status = %d and t.deleted=0 
			" . (is_null($dateRange) ? "" : " AND t.statusChangedDate BETWEEN '%s' AND '%s' ") . " 
			" . ($projectID == 0 ? " " : " AND t.projectId=%d " ). "
			" . ($activeUser->getRole() == 2 ? " AND u.id IN (SELECT userID FROM permissions WHERE projectID IN (SELECT projectID FROM permissions WHERE userID = {$activeUser->getId()}))" : "") . "
			AND u.id IS NOT NULL
			GROUP BY u.id 
			ORDER BY taskCount DESC";
		
		$format_array = array($doneTasks);
		if (!is_null($dateRange))
			$format_array = array_merge($format_array, array($dateRange["start"], $dateRange["end"]));
		if ($projectID != 0)
			$format_array = array_merge($format_array, array($projectID));
		
		$result = mysqli_query($this->conn, $this->format($query, $format_array));
		
		$users = array();
		while ($user = mysqli_fetch_assoc($result)){
			$user["imagesList"] = $this->getImagesByUserId($user["id"]);				
			$users[] = $user;
		}
		
		mysqli_free_result($result);
		return $users;
	}
	
	public function getUserData($userId){
		$query = "SELECT * FROM user where id=%d";
		$query = $this->format($query, array($userId));		
		$userDto = $this->execute($query, new UserMapper());
		return $userDto[0];
	}
	
	function getImagesByUserId($userId)
	{
		if (is_null($userId))
			return "";
		
		$dirPath = "imagesuser/".$userId;
		$filelist = array();
	    if(is_dir($dirPath) ){
	        if ($dh = opendir($dirPath)) {
		        while (($file = readdir($dh)) !== false) {
		        	if (($file != '.')&&($file != '..')&&($file != 'Thumbs.db')&& ($file != '.svn') )
		           		$filelist[] =  $file;
		        }
		        closedir($dh);
		    }
	    }
	    return count($filelist) > 0 ? implode("|", $filelist) : "noimage";
	}	
	
	function hasAdminContent($userId, $role)
	{
		if (is_null($userId))
			return 0;

		if($role == 0)
			return 0;
		else if($role == 1)
			return 1;
		else if(($role == 2) && ($this->getPUserAdminProjectsCount($userId) > 0))
			return 1;
			
		return 0;	
	}
	
	function getPUserAdminProjectsCount($userId)
	{
		$query = "SELECT count(*) as count from permissions where userID=%d and permission=1";
		$query = $this->format($query, array($userId));
		$countList = $this->execute($query, new CountMapper());
		return $countList[0];
	}
}
?>
